<!-- src/views/Product/ProductPageList.vue -->
<script setup lang="tsx">
import { ref, unref } from 'vue'
import { ElImage, ElMessage } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { getPageList, deleteProduct } from '@/api/product/admin'
import { useRouter } from 'vue-router'
import { ContentWrap } from '@/components/ContentWrap'

// 定义搜索参数类型
interface ProductPageListParams {
  keyword?: string
  skuId?: number
  skuCode?: string
  pvValue?: string
  minPrice?: number
  maxPrice?: number
  createTimeFrom?: string
  createTimeTo?: string
  pageNum: number
  pageSize: number
}

// 直接创建响应式的搜索参数对象
const searchParams = ref<ProductPageListParams>({
  keyword: '',
  skuId: undefined,
  skuCode: '',
  pvValue: '',
  minPrice: undefined,
  maxPrice: undefined,
  createTimeFrom: '',
  createTimeTo: '',
  pageNum: 1,
  pageSize: 10
})

// 创建 handleSearch 方法
const handleSearch = (callback?: () => void) => {
  // 重置页码为第一页
  searchParams.value.pageNum = 1
  // 执行回调函数（如重新获取数据）
  if (callback) callback()
}

// 创建 handleReset 方法
const handleReset = (callback?: () => void) => {
  // 重置搜索参数为初始值
  Object.assign(searchParams.value, {
    keyword: '',
    skuId: undefined,
    skuCode: '',
    pvValue: '',
    minPrice: undefined,
    maxPrice: undefined,
    createTimeFrom: '',
    createTimeTo: '',
    pageNum: 1,
    pageSize: 10
  })
  // 执行回调函数（如重新获取数据）
  if (callback) callback()
}

console.log(searchParams)

const { t } = useI18n()
const router = useRouter()

// 表格列定义
const columns = [
  {
    field: 'skuId',
    label: 'skuId',
    align: 'center'
  },
  {
    field: 'skuCode',
    label: 'skuCode'
  },
  {
    field: 'title',
    label: '商品标题'
  },
  {
    field: 'createdAt',
    label: '创建时间',
    sortable: true
  },
  {
    field: 'price',
    label: '价格'
  },
  {
    field: 'sort',
    label: '排序'
  },
  {
    field: 'mainImg',
    label: '主图',
    slots: {
      default: (data: any) => {
        const url = data.row.mainImg
        return (
          <ElImage
            style="width: 100px; height: 100px"
            src={url}
            fit="cover"
            preview-src-list={[url]}
            preview-teleported
          />
        )
      }
    }
  },
  {
    field: 'action',
    label: t('tableDemo.action'),
    slots: {
      default: (data: any) => {
        return (
          <div class="button-container">
            <el-button size="small" type="info" onClick={() => jumpDetailPage(data.row)}>
              详情
            </el-button>
            <el-button size="small" type="primary" onClick={() => jumpEditPage(data.row)}>
              编辑
            </el-button>
            <el-button size="small" type="danger" onClick={() => deleteHandle(data.row.skuId)}>
              删除
            </el-button>
          </div>
        )
      }
    }
  }
]

const loading = ref(true)
const total = ref(0)
const tableDataList = ref<ProductItem[]>([])

// 获取数据的方法
const fetchData = async () => {
  try {
    loading.value = true
    const params = unref(searchParams) || {
      pageNum: 1,
      pageSize: 10
    }

    // 过滤掉undefined的参数
    const filteredParams: Record<string, any> = {}
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== '') {
        filteredParams[key] = value
      }
    })

    const res = await getPageList(filteredParams)

    console.log('获取到的数据:', res)
    if (res && res.data.list && parseInt(res.data.total) > 0) {
      tableDataList.value = res.data.list
      total.value = res.data.total
    } else {
      tableDataList.value = []
      total.value = 0
    }
  } catch (err) {
    console.error(err)
    tableDataList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 跳转到编辑页面
const jumpEditPage = (row: ProductPageList) => {
  router.push({
    name: 'ProductEdit',
    query: { skuId: row.skuId }
  })
}

// 查看订单详情
const jumpDetailPage = (data: ProductPageList) => {
  router.push({
    name: 'ProductDetail',
    query: { skuId: data.skuId }
  })
}

// 删除处理
const deleteHandle = async (skuId: number) => {
  try {
    const res = await deleteProduct(skuId)

    if (res.code === 200) {
      ElMessage.success('删除成功')
      // 删除成功后重新加载数据
      fetchData()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (err) {
    console.error('删除商品失败:', err)
    ElMessage.error('删除商品失败')
  }
}
// 初始化加载数据
fetchData()
</script>

<template>
  <ContentWrap title="商品列表" message="展示商品主要信息等">
    <!-- 搜索表单 -->
    <div>
      <el-form v-if="searchParams" :model="searchParams" label-width="100px" inline>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="关键词">
              <el-input v-model="searchParams.keyword" placeholder="请输入关键词" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="SKU ID">
              <el-input-number
                v-model="searchParams.skuId"
                placeholder="请输入SKU ID"
                :min="0"
                controls-position="right"
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="SKU 编码">
              <el-input v-model="searchParams.skuCode" placeholder="请输入SKU编码" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="属性值">
              <el-input v-model="searchParams.pvValue" placeholder="请输入属性值" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="最低价格">
              <el-input-number
                v-model="searchParams.minPrice"
                placeholder="最低价格"
                :min="0"
                controls-position="right"
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="最高价格">
              <el-input-number
                v-model="searchParams.maxPrice"
                placeholder="最高价格"
                :min="0"
                controls-position="right"
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="创建开始时间">
              <el-date-picker
                v-model="searchParams.createTimeFrom"
                type="datetime"
                placeholder="选择开始时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="创建结束时间">
              <el-date-picker
                v-model="searchParams.createTimeTo"
                type="datetime"
                placeholder="选择结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24" class="text-right">
            <el-form-item>
              <el-button
                type="primary"
                @click="
                  () => {
                    handleSearch(fetchData)
                  }
                "
              >
                搜索
              </el-button>
              <el-button
                @click="
                  () => {
                    handleReset(fetchData)
                  }
                "
              >
                重置
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="tableDataList" border>
      <el-table-column
        v-for="column in columns"
        :key="column.field"
        :prop="column.field"
        :label="column.label"
        :sortable="column.sortable"
        :align="column.align || 'center'"
      >
        <template #default="scope" v-if="column.slots">
          <component :is="column.slots.default(scope)" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      v-model:current-page="searchParams.pageNum"
      v-model:page-size="searchParams.pageSize"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 50, 100]"
      @size-change="fetchData"
      @current-change="fetchData"
      class="mt-20px"
    />
  </ContentWrap>
</template>

<style scoped>
.mt-20px {
  margin-top: 20px;
}

.text-right {
  text-align: right;
}

.button-container {
  display: flex;
  flex-direction: column; /* 垂直排列，实现换行效果 */
  align-items: center; /* 右对齐 */
  gap: 8px; /* 按钮间距 */
}
.button-container :deep(.el-button) {
  margin: 0; /* 重置按钮默认外边距 */
}
</style>
